package servlet;

import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/updateBlog")
public class UpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        Integer blogId=Integer.parseInt(req.getParameter("blogId"));
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql = "UPDATE blog SET title = ?, content = ? WHERE blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, title);  // 新的标题
            statement.setString(2, content);  // 新的内容
            statement.setInt(3, blogId);  // 文章的 ID
            statement.executeUpdate();
            resp.sendRedirect("{\"success\": true, \"redirectUrl\": \"blog_list.jsp\"}");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
